'use strict';

const Controller = require('egg').Controller;

const MockData = require('../../mock')

const mysql = require('mysql')

const jwt = require('jsonwebtoken')

class HomeController extends Controller {

  async index() {
    const { ctx, app } = this;
    await MockData.forEach(item => {
      app.mysql.insert('lists', { title: item.title, introduce: item.introduce, img: item.img, price: item.price, id: item.id })

      ctx.body = {
        code: 200,
        msg: '成功'
      }
    })
  }

  //渲染
  async getList() {
    const { ctx, app } = this;
    const data = await app.mysql.select('lists')
    ctx.body = {
      code: 200,
      data
    }
  }
  //登录
  async Login() {
    const { ctx, app } = this;
    const { username, password } = ctx.request.body
    console.log(ctx.request.body);
    const post = await app.mysql.get('login', { username, password });
    const token = jwt.sign(username, "1901B")
    if (post) {
      ctx.body = {
        code: 1,
        msg: '登录成功',
        token,
        post
      }
    } else {
      ctx.body = {
        code: 0,
        msg: "登录失败"
      }
    }
  }


  //详情
  async detail() {
    const { ctx, app } = this;
    const { id } = ctx.request.body
    console.log(id);
    const data = await app.mysql.get("lists", { id })
    ctx.body = {
      code: 200,
      msg: "成功",
      data,
    }
  }
  //买房筛选
  async screening1() {
    const { app, ctx } = this;
    const { value } = ctx.request.body;
    const data = await app.mysql.select("lists", { where: { city: value } })

    if (value === '区域') {
      ctx.body = {
        code: 1,
        data
      }
    } else {
      ctx.body = {
        code: 500,
        data
      }
    }
  }

  //买房筛选
  async screening3() {
    const { app, ctx } = this;
    const { value } = ctx.request.body;
    const data = await app.mysql.select("lists", { where: { type: value } })

    if (value === '户型') {
      ctx.body = {
        code: 1,
        data
      }
    } else {
      ctx.body = {
        code: 500,
        data
      }
    }
  }
  //筛选
  async screening4() {
    const { app, ctx } = this;
    const { value } = ctx.request.body;
    const data = await app.mysql.select("lists", { where: { desc: value } })

    if (value === '筛选') {
      ctx.body = {
        code: 1,
        data
      }
    } else {
      ctx.body = {
        code: 500,
        data
      }
    }
  }
}

module.exports = HomeController;
